package com.shao.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2021/5/11
 * Time: 11:02
 * Description: No Description
 */

public class JdbcUtils {

    //数据库连接池对象
    private static DruidDataSource dataSource;
    static {
        try {
            //读取属性文件
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties properties = new Properties();
            //从流中加载到properties对象中
            properties.load(is);
            //创建数据库连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 获取数据库连接池的连接
     * @return 连接状态，如果获取成功了，连接返回连接状态，否则返回null
     */
    public static Connection getConnection(){

        Connection cnn = null;
        //获取连接池的连接
        try {
            cnn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return cnn;
    }

    /**
     * 关闭连接，放回数据连接池
     * @param cnn
     */
    public static void Close(Connection cnn){
        if(cnn!=null){
            try{
                cnn.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

